import { defineStore } from 'pinia';
import Cookies from 'js-cookie';
import { UserInfosStates, UserInfosState, WebsiteState } from './interface';
import { Session } from '/@/utils/storage';
import { useWebSite } from '/@/stores/websiteState';
import { ElMessage } from 'element-plus';
import { httpReqeustApi } from '/@/api/linxyun/base';

const httpReqeust = httpReqeustApi();
/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
	state: (): UserInfosStates => ({
		userInfos: {
			CustomerID: '',
			CustomerType: '',
			EntCode: '',
			UserName: '',
			LoginID: '',
			Extend: '',
			Token: '',
			UserID: '',
			UserRoles: [],
			UserType: '',
			photo: '',
			time: 0,
			roles: [],
			authBtnList: [],
		},
	}),
	actions: {
		async setUserInfos(loginUser: UserInfosState | null) {
			if (loginUser) {
				this.userInfos = loginUser;
			} else if (Session.get('userInfo')) {
				this.userInfos = Session.get('userInfo');
			}
			// 存储用户信息到浏览器缓存
			if (Session.get('userInfo')) {
				this.userInfos = Session.get('userInfo');
			} else {
				// 从本地存储中还原
				try {
					const user_loc = localStorage.getItem('user');
					if (user_loc && user_loc.length > 0) {
						const userInfos: any = JSON.parse(user_loc);
						this.userInfos = userInfos;
					} else {
						this.userInfos = null;
					}
				} catch (e) {
					console.log('read userinfo from local store exception!', e);
					this.userInfos = null;
				}
			}
			return this.userInfos;
		},
		// 模拟接口数据
		async getApiUserInfo(loginUser: any) {
			const resp = await httpReqeust.SyncPost('login', {}, loginUser);
			// const resp = await httpReqeust.SyncPost('/eslithe/linxyunLogin.action', {}, loginUser);
			console.log('wwwwwwwwwwww', resp);

			const user = resp.data;
			if (!user) {
				ElMessage.error('账户或密码错误！');
				Promise.reject();
				return null;
			}
			if (user.code === '1010') {
				ElMessage.error('账户或密码错误！');
				Promise.reject();
				return null;
			} else if (user.code === '1006') {
				ElMessage.error('账户不存在或身份有误！');
				Promise.reject();
				return null;
			} else {
				Cookies.set('UserName', user.UserName);
				Session.set('token', user.Token);

				// admin 页面权限标识，对应路由 meta.roles，用于控制路由的显示/隐藏
				// admin 按钮权限标识
				let adminAuthBtnList: Array<string> = ['btn.add', 'btn.del', 'btn.edit', 'btn.link'];
				// 用户信息模拟数据
				const userInfos: UserInfosState = {
					UserID: user.UserID as string,
					UserName: user.UserName as string,
					CustomerID: user.CustomerID as string,
					CustomerType: user.CustomerType as string,
					EntCode: user.EntCode as string,
					LoginID: user.LoginID as string,
					Extend: user.Extend as string,
					Token: user.Token as string,
					UserRoles: user.UserRoles as Array<string>,
					UserType: user.UserType as string,
					photo: 'https://img2.baidu.com/it/u=1978192862,2048448374&fm=253&fmt=auto&app=138&f=JPEG?w=504&h=500',
					time: new Date().getTime(),
					roles: ['admin'],
					authBtnList: adminAuthBtnList,
				};
				window.localStorage.setItem('user', JSON.stringify(userInfos));
				window.localStorage.setItem('name', user.UserName);
				window.localStorage.setItem('userType', user.UserType);
				window.localStorage.setItem('enterpriseID', user.CustomerID);
				this.setUserInfos(userInfos);
				const website: WebsiteState = { EntCode: '50', CustomerID: '0', SiteID: '24' };
				const storesWebsite = useWebSite();
				await storesWebsite.setWebSite(website);

				return userInfos;
			}
		},
		async frontLogout() {
			window.localStorage.removeItem('user');
			window.localStorage.removeItem('name');
			window.localStorage.removeItem('userType');
			window.localStorage.removeItem('enterpriseID');
			await this.setUserInfos(null);
			Cookies.set('UserName', '');
			Cookies.set('token', '');
			Session.set('UserName', '');
			Session.set('token', '');
		},
	},
});
